import { cache } from "./../../common/config/adapter";
import axios from "axios";
import fs from "fs";

interface clientDataFace {
  refresh_token: string;
  expires_in: number;
  session_key: string;
  access_token: string;
  scope: string;
}
let clientData: clientDataFace;
let taskList: AiimgCommunityTaskFace[] = [];
let isStart = false;
export default class extends think.Service {
  /**
   * 获取token
   * @param config 小程序信息
   * @returns token
   */
  getAccessToken(): Promise<string> {
    console.log("到了这里");
    const url = `https://aip.baidubce.com/oauth/2.0/token?client_id=${process.env.BAIDU_API_KEY}&client_secret=${process.env.BAIDU_API_SECRET}&grant_type=client_credentials`;
    var options = {
      method: "POST",
      url: url,
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    };

    return new Promise((resolve, reject) => {
      axios(options).then((response) => {
        const data = response.data;
        const accessToken = data.access_token;
        clientData = data;
        resolve(accessToken);
      });
    });
  }
  /**
   * 根据提交信息，生成百度绘画需要的数据格式
   * @param data
   * @returns
   */
  getData(data: AiimgCommunityFace): BaiduDataFace {
    const {} = data;
    let obj = {
      prompt: data.text,
      width: 1024,
      height: 1024,
      image_num: 1,
      change_degree: 1,
    };
    return obj;
  }
  async updateImg(data) {}
  /**
   * 根据任务id 查询当前的任务状态
   * @param datas
   */
  setTableTaskId = async (talkData: AiimgCommunityTaskFace) => {
    await axios({
      method: "POST",
      url: `https://aip.baidubce.com/rpc/2.0/ernievilg/v1/getImgv2?access_token=${clientData.access_token}`,
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      data: {
        task_id: talkData.taskId,
      },
    })
      .then(async (response) => {
        const data = response.data;
        const imageUrl =
          data.data.sub_task_result_list[0].final_image_list[0].img_url;
        await axios
          .get(imageUrl, { responseType: "stream" })
          .then(async (response) => {
            const fileService = think.service("file");
            await fileService.uploadAiImg(response.data).then((res: any) => {
              console.log("获取成功");

              const $model = think.model("ai_img");
              const $pk = $model.pk;

              $model.where({ taskId: talkData.taskId }).update({
                out_img: res.url,
                update_time: think.formatter(),
              });

              console.log("获取成功");
            });
          })
          .catch((error) => {
            console.error("Error saving image:", error);
          });
        talkData.callback && talkData.callback(data);
      })
      .finally(() => {});
  };
  /**
   * 提交绘画给百度，会回一个taskid，需记录数据库便于后续查询
   * @param datas
   */
  addImg = async (talkData: AiimgCommunityTaskFace) => {
    console.log(this.getData);
    let sData = this.getData(talkData);
    const that = this;
    await axios({
      method: "POST",
      url: `https://aip.baidubce.com/rpc/2.0/ernievilg/v1/txt2imgv2?access_token=${clientData.access_token}`,
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      data: sData,
    })
      .then((response) => {
        console.log("获取成功");
        const data = response.data;
        console.log(data);

        const $model = think.model("ai_img");
        const $pk = $model.pk;

        if (!talkData[$pk]) return;
        console.log(data);

        $model.where({ [$pk]: talkData[$pk] }).update({
          taskId: data.data.task_id,
          update_time: think.formatter(),
        });
      })
      .finally(() => {});
  };
  updateSql(id: IDType, data: any) {
    console.log("获取成功223");
    console.log(id);
  }
  async startTask() {
    if (taskList.length === 0 || isStart) return;
    isStart = true;
    if (think.isEmpty(clientData)) {
      await this.getAccessToken();
    }
    const data = taskList.shift();
    const functions = data.lx == "select" ? this.setTableTaskId : this.addImg;
    functions(data)
      .then((res) => {})
      .finally(() => {
        if (taskList.length > 0) {
          this.startTask();
        }

        isStart = false;
      });
  }
  /**
   * 添加绘画任务
   * @param data
   */
  addTask(data: AiimgCommunityFace) {
    const obj = {
      ...data,
      lx: "add",
    };

    taskList.push(obj);
    this.startTask();
  }
  /**
   * 添加查询任务
   * @param taskId
   * @returns
   */
  async selectTask(taskId: string) {
    return new Promise((resolve, reject) => {
      const obj = {
        taskId,
        lx: "select",
        callback: resolve,
      };
      taskList.push(obj);
      this.startTask();
    });
  }
}
